import 'dart:math';

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:fluwx/fluwx.dart';
import 'package:im_flutter_sdk/im_flutter_sdk.dart';
import 'package:image_picker/image_picker.dart';
import 'package:multi_image_picker/multi_image_picker.dart';
import 'package:provider/provider.dart';
import 'package:qunaimedical/init/provider.dart';
import 'package:qunaimedical/models/map_response.dart';
import 'package:qunaimedical/models/user.dart';
import 'package:qunaimedical/network/http.dart';
import 'package:qunaimedical/pages/conversations/photo_browser.dart';
import 'package:qunaimedical/utils/event_bus_manager.dart';
import 'package:qunaimedical/utils/sp_utils.dart';
import 'package:qunaimedical/values/urls.dart';

class CommonUtils {
  CommonUtils._internal();

  /// 判断登录密码：6~16位数字和字符组合
  static bool isLoginPassword(String input) {
    RegExp mobile = RegExp(r"(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,16}$");
    return mobile.hasMatch(input);
  }

  /// 6位数字验证码
  static bool isValidateCaptcha(String input) {
    RegExp mobile = RegExp(r"\d{6}$");
    return mobile.hasMatch(input);
  }

  /// 邮箱匹配
  static bool matchEmail(String email) {
    var re =
        "[\\w!#\$%&'*+/=?^_`{|}~-]+(?:\\.[\\w!#\$%&'*+/=?^_`{|}~-]+)*@(?:[\\w](?:[\\w-]*[\\w])?\\.)+[\\w](?:[\\w-]*[\\w])?";
    return RegExp(re).hasMatch(email);
  }

  /// 隐藏键盘
  static void hideKeyboard(BuildContext context) {
    FocusScope.of(context).requestFocus(FocusNode());
  }

  /// 将图片转换成MapEntry，上传使使用。
  static Future<List<MapEntry<String, MultipartFile>>> images2MapEntry(
      List<Asset> images) async {
    List<MapEntry<String, MultipartFile>> entries = [];
    for (int i = 0; i < images.length; i++) {
      Asset e = images[i];
      int randomNum = (Random().nextDouble() * 10000).toInt();
      String imageName =
          '${DateTime.now().millisecondsSinceEpoch ~/ 1000}_$randomNum.jpg';
      ByteData byteData = await e.getByteData(quality: 80);
      entries.add(
        MapEntry(
          "file",
          MultipartFile.fromBytes(
            byteData.buffer.asUint8List(),
            filename: imageName,
          ),
        ),
      );
    }
    return entries;
  }

  /// 将图片转换成MapEntry，上传使使用。
  static Future<List<MapEntry<String, MultipartFile>>> files2MapEntry(
      List<PickedFile> files) async {
    List<MapEntry<String, MultipartFile>> entries = [];
    for (int i = 0; i < files.length; i++) {
      entries.add(
        MapEntry(
          "file",
          await MultipartFile.fromFile(files[i].path),
        ),
      );
    }
    return entries;
  }

  /// 刷新个人信息
  static Future refreshProfile(BuildContext context) async {
    User user = context.read<StoreInfo>().user;
    if (user == null) {
      return;
    }
    var data = await XHttp.get('${Urls.GET_DOCTOR_PROFILE}?id=${user.id}');
    if (data != null) {
      MapResponse response = MapResponse.fromJson(data);
      if (response.code == 1) {
        user.fullname = response.data['fullname'];
        user.authStatus = response.data['authStatus'];
        user.avatar = response.data['avatar'];
        context.read<StoreInfo>().updateUser(user);
        eventBus.fire(EventBusManager(EventBusManager.profileRefresh));
      }
    }
  }

  static void openGallery(
      BuildContext context, List<String> imagePaths, int index) {
    Navigator.of(context).push(FadeRoute(
      page: PhotoBrowser(
        imgDataArr: imagePaths,
        index: index,
      ),
    ));
  }

  /// 判定是否为数字
  static bool isNumeric(String s) {
    if (s == null) {
      return false;
    }
    return double.tryParse(s) != null;
  }

  /// 获取未读消息数量。
  static void getUnreadMsgCount(BuildContext context) async {
    int count = 0;
    if (SPUtils.getUser() != null) {
      try {
        List<EMConversation> conList =
            await EMClient.getInstance.chatManager.loadAllConversations();
        conList.forEach((conv) {
          count += conv.unreadCount;
        });
      } on EMError catch (e) {
        print('操作失败，原因是: $e');
      }
    }
    context.read<StoreInfo>().updateUnreadMsgCount(count);
  }

  /// 退出登录
  static void logout(BuildContext context) {
    context.read<StoreInfo>().clear();
  }

  /// 分享链接到微信
  static void shareLinkToWinXin(BuildContext context, String link) {
    showModalBottomSheet(
        context: context,
        backgroundColor: Colors.transparent,
        builder: (c) {
          return Container(
            height: 150 + MediaQuery.of(context).padding.bottom,
            decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.only(
                  topLeft: Radius.circular(20),
                  topRight: Radius.circular(20),
                )),
            child: Column(
              children: [
                Container(
                  child: Text(
                    '分享至',
                    style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
                  ),
                  padding: EdgeInsets.all(16),
                ),
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                  children: [
                    _buildShareOption(context, 0, link),
                    _buildShareOption(context, 1, link),
                  ],
                ),
              ],
            ),
          );
        });
  }

  static Widget _buildShareOption(
      BuildContext context, int index, String source) {
    String iconPath;
    String title;
    switch (index) {
      case 0:
        iconPath = 'assets/images/ic_wx_timeline.png';
        title = '朋友圈';
        break;
      case 1:
        iconPath = 'assets/images/ic_wechat.png';
        title = '微信好友';
        break;
      default:
    }
    return InkWell(
      onTap: () {
        Navigator.pop(context);
        switch (index) {
          case 0:
            shareToWeChat(
                WeChatShareWebPageModel(source, scene: WeChatScene.TIMELINE));
            break;
          case 1:
            shareToWeChat(
                WeChatShareWebPageModel(source, scene: WeChatScene.SESSION));
            break;
        }
      },
      child: Column(children: [
        Container(
          child: Image.asset(iconPath, width: 30),
          padding: EdgeInsets.only(left: 16, top: 16, right: 16, bottom: 5),
        ),
        Text(
          title,
          style: TextStyle(fontSize: 12),
        ),
      ]),
    );
  }

  static Future registerIM(BuildContext context, String username) async {
    try {
      String id = await EMClient.getInstance.createAccount(username, '000000');
      print('注册账号：$id');
      loginIM(context, username);
    } on EMError catch (e) {
      print('注册失败，原因是: $e');
    }
  }

  static Future loginIM(BuildContext context, String username) async {
    try {
      await EMClient.getInstance.logout();
      await EMClient.getInstance.login(username, '000000');
      CommonUtils.getUnreadMsgCount(context);
    } on EMError catch (e) {
      if (e.code == 204) {
        registerIM(context, username);
      }
    }
  }
}

enum FunctionType { video, image }
